#!/usr/bin/env python3
"""
Git 仓库初始化脚本
一键完成克隆远程仓库 → 添加 README → 提交并推送的自动化流程
"""

import subprocess
import sys
import os
from pathlib import Path

def run_command(command, cwd=None):
    """执行 shell 命令并返回结果"""
    try:
        result = subprocess.run(
            command,
            shell=True,
            cwd=cwd,
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        print(f"错误: {e.stderr}")
        sys.exit(1)

def git_init_automation(repo_url, local_dir=None):
    """自动化 Git 仓库初始化流程"""
    
    # 如果没有指定本地目录，从 URL 中提取仓库名
    if not local_dir:
        local_dir = repo_url.split('/')[-1].replace('.git', '')
    
    print(f"开始初始化仓库: {repo_url}")
    print(f"本地目录: {local_dir}")
    
    # 1. 克隆远程仓库
    print("1. 克隆远程仓库...")
    run_command(f"git clone {repo_url}")
    
    # 2. 进入目录
    repo_path = Path(local_dir)
    if not repo_path.exists():
        print(f"错误: 目录 {local_dir} 不存在")
        sys.exit(1)
    
    # 3. 添加 README.md
    print("2. 添加 README.md...")
    readme_path = repo_path / "README.md"
    with open(readme_path, "a", encoding="utf-8") as f:
        f.write("\n# 项目简介\n\n这是一个自动初始化的 Git 仓库。\n")
    
    # 4. 添加文件到暂存区
    print("3. 添加文件到暂存区...")
    run_command("git add README.md", cwd=repo_path)
    
    # 5. 提交更改
    print("4. 提交更改...")
    run_command('git commit -m "add README"', cwd=repo_path)
    
    # 6. 重命名分支为 main
    print("5. 重命名分支为 main...")
    try:
        run_command("git branch -m main", cwd=repo_path)
    except:
        print("分支可能已经是 main，跳过重命名")
    
    # 7. 推送到远程仓库
    print("6. 推送到远程仓库...")
    run_command("git push -u origin main", cwd=repo_path)
    
    print("\n✅ 仓库初始化完成！")
    print(f"本地路径: {os.path.abspath(local_dir)}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("使用方法: python git_init.py <仓库URL> [本地目录名]")
        print("示例: python git_init.py https://gitcode.com/gcw_GI6ls4dg/1.git")
        sys.exit(1)
    
    repo_url = sys.argv[1]
    local_dir = sys.argv[2] if len(sys.argv) > 2 else None
    
    git_init_automation(repo_url, local_dir)
